﻿using iTextSharp.text.pdf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools.Helper;

namespace Tools
{
    public partial class MicrosoftCalendar : Base
    {
        public MicrosoftCalendar()
        {
            InitializeComponent();
            base.SetDefaultLocation();

            DataBindTime(DateTime.Now.ToString("HH:00"));
            GetLogAsync(DateTime.Now);
        }

        string timezone = "China Standard Time";
        string ribao = "AQMkADAwATY3ZmYAZS1hOGQ5LWI1NjEtMDACLTAwCgBGAAAD63Q7MReF3U_07sh48tkOlAcA2ME1sP4OHkG8uWM1VkagLgAAAgEGAAAA2ME1sP4OHkG8uWM1VkagLgADaKnBpQAAAA==";
        string[] time = { "00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30" };
        string[] time1 = { "00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30" };
        /// <summary>
        /// 时间 格式 HH:00
        /// </summary>
        /// <param name="dateTimeStr"></param>
        public void DataBindTime(string dateTimeStr)
        {
            cob_start.DataSource = time;
            cob_start.SelectedItem = dateTimeStr;
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            GetLogAsync(DateTime.Now);
        }

        private void btn_month_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/month");
        }

        private void btn_day_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/day");
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            GetLogAsync(this.monthCalendar1.SelectionEnd);
        }

        private async void btn_add_ClickAsync(object sender, EventArgs e)//添加事件
        {
            if (chb_all.Checked)
            {
                var time = DateTime.Now.ToShortDateString();
                AddEvent(txt_title.Text, "沈阳市, 中国辽宁省沈阳市", time, time, true);
            }
            else
            {
                var start = Picker_Start.Value.ToShortDateString() + " " + cob_start.Text;
                var end = Picker_End.Value.ToShortDateString() + " " + cob_end.Text;

                AddEvent(txt_title.Text, "沈阳市, 中国辽宁省沈阳市", start, end, false);
            }
            GetLogAsync(DateTime.Now);

            txt_title.Text = "";
            MessageBox.Show("添加事件成功!");
        }

        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="title"></param>
        /// <param name="location"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="isAllDay"></param>
        /// <returns></returns>
        public void AddEvent(string title, string location, string starttime, string endtime, bool isAllDay)
        {
            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events";
            var obj = new
            {
                isAllDay = isAllDay,
                isReminderOn = false,//不提醒
                subject = title,
                body = new
                {
                    contentType = "HTML",
                    content = ""
                },
                start = new
                {
                    dateTime = starttime,
                    timeZone = timezone
                },
                end = new
                {
                    dateTime = endtime,
                    timeZone = timezone
                },
                location = new
                {
                    displayName = "中国,辽宁,沈阳"
                },
                allowNewTimeProposals = true,
                transactionId = Guid.NewGuid()
            };
            MicrosoftToken.HttpRequest(url, JsonConvert.SerializeObject(obj));
        }

        /// <summary>
        /// 获取事件
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async void GetLogAsync(DateTime time)
        {
            await MicrosoftToken.SetTokenAsync();
            var select = $"subject,body,bodyPreview,organizer,attendees,start,end,location";
            var filter = $"start/dateTime ge '{time.ToString("yyyy-MM-dd")}' and end/dateTime lt '{time.AddDays(1).ToString("yyyy-MM-dd")}'";
            var orderby = $"start/dateTime";
            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events?$filter={filter}&$orderby={orderby}&$select={select}";
            var res = MicrosoftToken.HttpRequest(url, "", "get");

            var timeStr = DateTime.Now.ToString("HH:mm");
            var dic = new Dictionary<string, bool>()
            {
                {"上午",true },
                {"下午",true },
                {"明日计划",true },
                {"晚上",true }
            };


            //列出事件。
            var str = new StringBuilder();

            var list = JsonConvert.DeserializeObject<dynamic>(res).value;
            foreach (var item in list)
            {
                var nr = item["subject"].ToString();

                var start = Convert.ToDateTime(item["start"]["dateTime"].ToString());
                var end = Convert.ToDateTime(item["end"]["dateTime"].ToString());
                timeStr = end.ToString("HH:mm");

                var timeName = TimeName(dic, start.ToString("HH:mm"), end.ToString("HH:mm"));
                if (!string.IsNullOrEmpty(timeName))
                {
                    str.Append(timeName + "\r\n");
                }
                var haoshi = (end - start).TotalHours;
                var hs = "";
                if (haoshi >= 1)
                {
                    hs = haoshi + "小时";
                }
                else
                {
                    hs = (haoshi * 60) + "分钟";
                }
                if (start == end)//明日计划
                {
                    nr = item["subject"].ToString();
                }
                else
                {
                    nr = string.Format("[{0}-{1} {2}]:{3}", start.ToString("HH:mm"), end.ToString("HH:mm"), hs, item["subject"].ToString());
                }
                str.Append(nr + "\r\n");
            }
            txt_log.Text = str.ToString();
            cob_start.SelectedItem = timeStr;
        }

        /// <summary>
        /// 设置时间名称
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        private string TimeName(Dictionary<string, bool> dic, string start, string end)
        {
            var result = "";
            if (dic["明日计划"] && start == "17:30" && end == "17:30")
            {
                dic["明日计划"] = false;
                result = "明日计划";
            }
            else if (dic["上午"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01") && Convert.ToDateTime("2018-01-01 " + start) < Convert.ToDateTime("2018-01-01 12:00"))
            {
                dic["上午"] = false;
                result = "上午";
            }
            else if (dic["下午"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01 12:00") && Convert.ToDateTime("2018-01-01 " + start) < Convert.ToDateTime("2018-01-01 18:00"))
            {
                dic["下午"] = false;
                result = "下午";
            }
            else if (dic["晚上"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01 18:00"))
            {
                dic["晚上"] = false;
                result = "晚上";
            }
            return result;
        }

        private void cob_start_SelectedIndexChanged(object sender, EventArgs e)
        {
            cob_end.SelectedItem = Convert.ToDateTime(Picker_Start.Value.ToShortDateString() + " " + cob_start.Text).AddHours(1).ToString("HH:mm");

            var flag = false;
            cob_end.Items.Clear();

            foreach (var item in time1)
            {
                if (item == cob_start.Text)
                {
                    flag = true;
                }
                if (flag)
                {
                    cob_end.Items.Add(item);
                }
            }
            cob_end.SelectedItem = Convert.ToDateTime("2018-08-16 " + cob_start.Text).AddHours(1).ToString("HH:mm");
        }

        private void chb_tomorrow_CheckedChanged(object sender, EventArgs e)
        {
            if (chb_tomorrow.Checked)
            {
                txt_title.Text = "1.计划\r\n2.计划\r\n3.计划";
                cob_start.Text = "17:30";
                cob_end.Text = "17:30";
            }
            else
            {
                txt_log.Text = "";
            }
        }
    }
}
